<?php


namespace App\Services;


use App\Constants\AdvConfigConstant;
use App\Constants\IntegralLogTypeConstant;
use App\Constants\MemberTaskConstant;
use App\Exceptions\BusinessException;
use App\Models\MemberTask;
use App\Models\MemberTaskLog;
use Illuminate\Support\Facades\DB;

class MemberTaskService
{
    public function handle(int $memberId, string $slug, ?string $advId, ?string $miniType): ?array
    {
        if (!in_array($slug, array_keys(MemberTaskConstant::MAP))) {
            throw new BusinessException('任务标识错误');
        }

        if ($slug == MemberTaskConstant::SLUG_BY_READ_ADV_VIDEO) {
            if (!$advId) {
                throw new BusinessException('广告位id不能为空');
            }

            $id = getMiniSettings($miniType, AdvConfigConstant::ADV_GROUP, AdvConfigConstant::INCENTIVE_ADV_ID);
            if ($id != $advId) {
                throw new BusinessException('广告位id错误');
            }
        }

        $info = MemberTask::query()->where([
            'slug'      => $slug,
            'mini_type' => $miniType
        ])->first();
        if (!$info) {
            throw new BusinessException('任务标识错误');
        }

        if (!$info->status || !$info->max_finish || $info->integral <= 0) {
            return null;
        }

        $finishNum = MemberTaskLog::query()->where([
            'member_id' => $memberId,
            'slug'      => $slug,
            'mini_type' => $miniType
        ])->whereDate('created_at', '=', date('Y-m-d'))->count();

        if ($info->max_finish <= $finishNum) {
            return null;
        }

        try {
            DB::beginTransaction();

            $logId = app(IntegralService::class)->store($miniType, $memberId, $info->integral, IntegralLogTypeConstant::TYPE_BY_TASK, $info->remark);

            MemberTaskLog::create([
                'member_id' => $memberId,
                'task_id'   => $info->id,
                'log_id'    => $logId,
                'slug'      => $info->slug,
                'integral'  => $info->integral,
                'mini_type' => $miniType,
            ]);

            DB::commit();
        } catch (BusinessException $e) {
            DB::rollBack();
            throw $e;
        } catch (\Exception $e) {
            DB::rollBack();
            log_exception('完成任务奖励积分异常', $e->getMessage());
            throw new BusinessException('完成任务奖励积分异常');
        }

        return [
            'integral' => $info->integral,
        ];
    }
}
